import _ from "lodash";
import { RouteRecordRaw } from "vue-router";
import { titleCaptionMap } from "@/common";

const demoComponents = import.meta.glob("../demo/*.vue");

function getDemoName(path: string) {
  return path.slice(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
}

export const demos = await Promise.all(
  Object.keys(demoComponents).map(async (k) => {
    const demoName = getDemoName(k);
    // () => import('xxx') 返回的是 Promise<Module> 类型
    const component = ((await demoComponents[k]()) as any).default;
    const order = _.parseInt(demoName.slice(0, 3));
    const caption = `${_.padStart(_.toString(order), 3, "0")} ${
      component.title
    }`;
    titleCaptionMap.set(component.title, caption);
    return {
      path: demoName,
      name: demoName,
      component: component,
      meta: {
        title: caption,
      },
      order,
    };
  })
);
// demos.sort((e1, e2) => (e1.order > e2.order ? 1 : -1));

demos.forEach((demo) => {
  demo.name = demo.name || demo.path;
});

const routes: RouteRecordRaw[] = [
  {
    name: "demo-layout",
    path: "/",
    children: demos,
  },
];

export default routes;
